//初始画

const acticle = document.querySelector('#acticle') // 编辑2个输入框
const squareSize = 50
const gameGrid =[8,10]
const currentGrid = Array.from({ length: 10 }, () => Array(10).fill(0));
const ImageGrid = Array.from({ length: 10 }, () => Array(10).fill(null));
const XY = [280,70]

let newIndex;
let oldIndex = 0

const cubeKey = ['cube0','cube1','cube2','cube3']
const cubeSelect = [0x70A6CE,0xC23A35,0x59A58D,0xF1D67E]
const cubeColor = ['#70A6CE','#C23A35','#59A58D','#F1D67E']
let cubeString= ['蓝色','红色','绿色','黄色']
let original = "" // 100位数字
let selectedCircle;
let arrow;
let gameIndex = 0
let gameHistory = []
let gameOn = false
let stepStart = 3
let stepCount = 3
let step;
let type = 'edit'  // game edit test

let pageIndex =0 
let gameNowIndex = 0
class StartScene extends Phaser.Scene {
  constructor() {
      super({ key: 'StartScene' });
  }

  preload() {
      this.load.audio('click', 'audio/click.mp3');
  }

  create() {

       showSheZhi();
       this.sound.add('click');
     
      // 标题文本
      const title = this.add.text(
          550,
          200,
          '溢彩画',
          {
              fontFamily: 'Arial',
              fontSize: 64,
              color: '#ffffff',
              stroke: '#000000',
              strokeThickness: 6
          }
      ).setOrigin(0.5);
      this.add.text(550,260,'制作人员：咕噜水蜜桃',
      {
        fontFamily: 'Arial',
        fontSize: 14,
        color: '#ffffff',
    }).setOrigin(0.5);

      // 开始按钮
      const startButton = this.add.text(
          550,
          350,
          '开始游戏',
          {
              fontFamily: 'Arial',
              fontSize: 32,
              color: '#ffffff',
              backgroundColor: '#333333',
              padding: { x: 20, y: 10 }
          }
      ).setOrigin(0.5);

      const endButton = this.add.text(
        550,
        430,
        '退出游戏',
        {
            fontFamily: 'Arial',
            fontSize: 32,
            color: '#ffffff',
            backgroundColor: '#333333',
            padding: { x: 20, y: 10 }
        }
    ).setOrigin(0.5);

      // 添加按钮交互
      startButton.setInteractive();
      startButton.on('pointerover', () => {
          startButton.setStyle({ fill: '#ff0000' });
      });
      startButton.on('pointerout', () => {
          startButton.setStyle({ fill: '#ffffff' });
      });
      startButton.on('pointerdown', () => {
          this.sound.play('click');
          closeSheZhi();
          this.scene.start('ListScene'); // 切换到主游戏场景
      });
      endButton.setInteractive();
      endButton.on('pointerover', () => {
        endButton.setStyle({ fill: '#ff0000' });
    });
    endButton.on('pointerout', () => {
        endButton.setStyle({ fill: '#ffffff' });
    });
      endButton.on('pointerdown', () => {
        this.sound.play('click');
        exitGame();
        
    
    });
  }
}
let music = null
let music2 = null;
let frameCounter = 0;
let buttons = null
class MainScene extends Phaser.Scene {
  constructor() {
    super({ key: 'MainScene' }); 
    this.gameName = null
    this.acticleName = null
    this.click = null
    this.t =null
  }

  preload() {
    this.load.image('arrow', 'img/arrow.png')
    this.load.image('back',"img/back_l.png")
    this.load.image('re','img/re.png')
    this.load.image('arrow2', 'img/arrow2.png')
    this.load.image('cube0', "img/cube0_light_9.png");
    this.load.image('cube1', "img/cube1.png");
    this.load.image('cube2', "img/cube2.png");
    this.load.image('cube3', "img/cube3.png");
    this.load.audio('click', 'audio/click.mp3')
    this.load.audio('c', 'audio/e.mp3')
    this.load.image('win',"img/win.png")
    this.load.audio('d', 'audio/d.mp3')
  }
  
  // 场景创建方法
  create() {
    // this.events.once("shutdown", () => {
    //   acticle.style.display = 'none';
    // });
    this.click = this.sound.add('click');

    music2 = this.sound.add('d');
    music= this.sound.add('c');
    // 设置背景
    const back = this.add.image(1000, 40, 'back')
    back.setInteractive().on('pointerdown', () => {
      this.toClick()
      this.scene.start('ListScene');
    });
    this.add.text(
      20,
      20,
      '溢彩画',
      {
          fontFamily: 'Arial',
          fontSize: 18,
          color: '#7F7042',
          stroke: '#000000',
          strokeThickness: 6
      }
  ).setOrigin(0,0);
  this.add.text(
    20,
    50,
    '剩余步数:',
    {
        fontFamily: '黑体',
        fontSize: 24,
        color: '#ffffff',
        stroke: '#000000',
        strokeThickness: 6
    }
).setOrigin(0,0);
  step =  this.add.text(
  130,
  42,
  stepCount,
  {
      fontFamily: '黑体',
      fontSize: 34,
      color: '#ffffff',
      stroke: '#000000',
      strokeThickness: 6
  }
).setOrigin(0,0);
    this.addQiPan();
    this.addList();
    if(type !== 'game'){
      const startButton = this.add.text(
        550,
        500,
        '开始测试',
        {
            fontFamily: 'Arial',
            fontSize: 24,
            color: '#ffffff',
            backgroundColor: '#333333',
            padding: { x: 20, y: 10 }
        }
    ).setOrigin(0.5);

    // 添加按钮交互
    startButton.setInteractive();
    startButton.on('pointerover', () => {
        startButton.setStyle({ fill: '#ff0000' });
    });
    startButton.on('pointerout', () => {
        startButton.setStyle({ fill: '#ffffff' });
    });
    startButton.on('pointerdown', () => {
      this.toClick()
      if(type !== 'edit'){
        showMessage('已结束')
        type = 'edit'
        startButton.text = '开始测试'
        return
      }
      showMessage('开始测试了')
      startButton.text = '结束测试'
      stepCount = stepStart
      step.text = stepStart
      original = currentGrid.flat().join('')
      type = 'test'
    });
    buttons = startButton
   
    this.gameName = this.add.text(
      55,
      105,
      '关卡名',
      {
          fontFamily: 'Arial',
          fontSize: 22,
          color: '#555',
      }
  ).setOrigin(0.5).setInteractive().on('pointerdown',()=>{
    this.toText(1)
  });
  this.acticleName = this.add.text(
    55,
    135,
    '制作人',
    {
        fontFamily: 'Arial',
        fontSize: 22,
        color: '#555',
    }
).setOrigin(0.5).setInteractive().on('pointerdown',()=>{
  this.toText(2)
});



    }else{
      const a = this.add.image(280, 410 + XY[1], 'arrow')
      a.setOrigin(0, 0);
      a.displayHeight = 20
      a.displayWidth = 20
      this.add.text(
        305,
        410 +  XY[1],
        '将色块全部变成 ',
        {
            fontFamily: 'Arial',
            fontSize: 16,
            color: '#ffffff',
            stroke: '#000000',
            strokeThickness: 6
        }
    ).setOrigin(0,0);
     const  b = parseInt(original[98])
     this.add.text(
      425,
      411 +  XY[1],
      '【'+ cubeString[b] + '】',
      {
          fontFamily: '黑体',
          fontSize: 18,
          color: cubeColor[b],
          stroke: '#000000',
          strokeThickness: 6
      }
  ).setOrigin(0,0);
    }
    this.input.on('pointerdown', (pointer) => {
      if(pointer.x < XY[0] -100 || pointer.x > XY[0] + gameGrid[1] * squareSize) return
      if(pointer.y < XY[1] -100 || pointer.y > XY[1] + gameGrid[0] * squareSize) return
      if(type == 'edit'){
        this.startPoint = new Phaser.Math.Vector2(pointer.x, pointer.y);
      // 创建一个初始的矩形框
      this.box = this.add.rectangle(pointer.x, pointer.y, 0, 0, 0x00ff00, 0.3);
      }
      
  });

  // 监听鼠标移动事件
  this.input.on('pointermove', (pointer) => {
      if (this.startPoint && type == 'edit') {
          const width = pointer.x - this.startPoint.x;
          const height = pointer.y - this.startPoint.y;
          this.box.setPosition(this.startPoint.x + width / 2, this.startPoint.y + height / 2);
          this.box.setSize(Math.abs(width), Math.abs(height));
      }
  });

  // 监听鼠标释放事件
  this.input.on('pointerup', (pointer) => {
      if (this.startPoint && type == 'edit') {
        const left = this.box.x - this.box.width / 2
        const right = this.box.x + this.box.width / 2
        const top = this.box.y - this.box.height / 2
        const bottom = this.box.y + this.box.height / 2
        const arr2 = [Math.max(0,Math.floor((left -XY[0]) / squareSize)),Math.min(gameGrid[1] -1,Math.floor((right -XY[0]) / squareSize))]
        const arr1 = [Math.max(0,Math.floor((top -XY[1]) / squareSize)),Math.min(gameGrid[0] -1,Math.floor((bottom -XY[1]) / squareSize))]
        this.startPoint = null 
        this.box.destroy()
        this.box = null
        if (arr1[0] > arr1[1] || arr2[0] > arr2[1]) return
        for (let row = arr1[0]; row < arr1[1] + 1; row++) {
          for (let col = arr2[0]; col <arr2[1]+ 1; col++) {
               currentGrid[row][col] = newIndex
              if(ImageGrid[row][col]){
                ImageGrid[row][col].setTexture(cubeKey[newIndex])
              }
          }
        }     
         
      }
    
  });
    
  }

  toClick(){
      this.click.play();
  }

  selectCircle(circle,i) {
    // 移除之前选中的圆环和箭头
    if(i == newIndex){
      return
    }
    newIndex = i
    this.toClick()
    if (selectedCircle) {
        selectedCircle.destroy();
        arrow.destroy();
    }

    // 创建新的白色圆环
    selectedCircle = this.add.circle(circle.x, circle.y, circle.radius, 0xFFFFFF, 0);
    selectedCircle.setStrokeStyle(2, 0xFFFFFF);

    // 创建箭头指向选中的圆
    arrow = this.add.image(circle.x + circle.radius + 10, circle.y, 'arrow2')
            .setScale(0.2)
           .setAngle(90);
}
toText(t){
  let model =  document.querySelector('#acticle');
  model.style.display = 'block';
  let input = document.querySelector('#input');
  input.focus()
  if(t === 1){
    input.placeholder = this.gameName.text
  }else {
    input.placeholder = this.acticleName.text
  }
  this.t = t
  input.style.display = 'block';
  model.addEventListener('click', () => {
     if(input.value){
       if(this.t === 1){
        this.gameName.text = input.value;
       }else{
        this.acticleName.text = input.value;
       }
       input.value = '';
     }
     input.placeholder = '';
     model.style.display = 'none';
     input.style.display = 'none';
 });


}
addWin() {
  // 创建弹出框背景

  const allInteractiveElements = this.children.list.filter(child => child.input && child.input.enabled);
  allInteractiveElements.forEach(element => {
      element.input.enabled = false;
  });
   music2.play()
  const bg = this.add.graphics();
  bg.fillStyle(0x000000, 0);
  bg.fillRect(0, 0, this.cameras.main.width, this.cameras.main.height);
  bg.setDepth(1000); 
 

  const popupBackground = this.add.graphics();
  popupBackground.fillStyle(0xBAE4FA, 1);
  const popupWidth = 400;
  const popupHeight = 220;  // 增加高度以容纳标题
  const popupX = (this.cameras.main.width - popupWidth) / 2;
  const popupY = (this.cameras.main.height - popupHeight) / 2;
  popupBackground.fillRect(popupX, popupY, popupWidth, popupHeight);
  // 设置弹出框背景的深度，使其位于背景之上
  popupBackground.setDepth(1001); 

  // 添加标题
  const titleText = this.add.image(
      popupX + popupWidth / 2,
      popupY ,
      'win'
  )
  titleText.displayWidth = 160
  titleText.displayHeight = 160;
  // 设置标题的深度，使其位于背景之上
  titleText.setDepth(1001); 
  this.add.text(
    popupX + popupWidth / 2,
    popupY + 100,
    '胜利',
    { fontSize: '36px', 
    color:"#FFA500",
   fontFamily: 'Arial' 
  }
  ).setOrigin(0.5, 0.5).setDepth(1001);
  
  // 创建通用按钮函数
  function createPopupButton(x, y, text, color, callback) {
      const button = this.add.text(x, y, text, {
          fontSize: '22px',
          color: color,
          backgroundColor: '#FFA500',
          padding: { x: 20, y: 10 },
          align: 'center'
      }).setOrigin(0.5);
      button.setInteractive().on('pointerdown', callback);
      // 设置按钮的深度，使其位于背景之上
      button.setDepth(1002); 
      return button;
  }

  // 创建按钮
  const buttonY = popupY + popupHeight - 60;
  const confirmButton = createPopupButton.call(
      this,
      popupX + popupWidth * 0.3,
      buttonY,
      '返 回',
      '#000000',
      () => {
          this.toClick()
          music2.stop()
          hidePopup();
          this.scene.start('ListScene');

      }
  );

  const cancelButton = createPopupButton.call(
      this,
      popupX + popupWidth * 0.7,
      buttonY,
      '下一关',
      '#000000',
      () =>{
          this.toClick()
        if(gameNowIndex === gameList.length-1){
          showMessage('已经是最后一关了');
          return;
        }
        gameNowIndex++;
        music2.stop()
        hidePopup();
        original = decompressNumberString(gameList[gameNowIndex].shareCode.split(";")[0])
        type = 'game'
        stepStart = parseInt(original[99])
        stepCount = stepStart
        this.scene.start('MainScene');
      }
  );

  // 统一隐藏弹出框方法
  function hidePopup() {
      popupBackground.clear();
      bg.clear();
      titleText.destroy();
      confirmButton.destroy();
      cancelButton.destroy();
      allInteractiveElements.forEach(element => {
        element.input.enabled = true;
    });
  }
}

resetGame() {
  // 重新启动当前场景
  this.toClick()
  let count = 0
  for (let row = 0; row < gameGrid[0]; row++) {
    for (let col = 0; col < gameGrid[1]; col++) {
        let a = +original[count]
        count++
         currentGrid[row][col] = a 
         ImageGrid[row][col].setTexture(cubeKey[a])
    }
}
  stepCount = stepStart
  step.text = stepStart
}
addList(){
  let colors = [];
  if(type == 'game'){
    const cs = [...new Set(original.slice(0, 80).split(''))]
    for (let i = 0; i < cs.length; i++) {
      colors.push(cubeSelect[parseInt(cs[i])])
    }
  }else{
    colors = cubeSelect
  }
        const circleRadius = 25;
        const circleSpacing = 60;

        // 循环创建圆形
        for (let i = 0; i < colors.length; i++) {
            const circle = this.add.circle(850, XY[1] + 30 + i * circleSpacing, circleRadius, colors[i]);
            circle.setInteractive();
            circle.on('pointerdown', () => {

                this.selectCircle(circle,cubeSelect.findIndex(color => color === colors[i]));
               
            });
            if(i === 0){
              this.selectCircle(circle,cubeSelect.findIndex(color => color === colors[i]));
            }
        }
        this.add.image(850, 150 + colors.length * circleSpacing, 're')
        .setDisplaySize(squareSize, squareSize)
        .setInteractive().on('pointerdown', () => {
          this.resetGame()
    })
}
  addQiPan(){
    let count = 0
              for (let row = 0; row < gameGrid[0]; row++) {
                  for (let col = 0; col < gameGrid[1]; col++) {
                      let squareType;
                      let a = original[count++]
                      squareType = 'cube' + a
                      const x = col * squareSize;
                      const y = row * squareSize;
                      // 添加格子到场景
                      const square = this.add.image(x + squareSize / 2 +XY[0], y + squareSize / 2 + XY[1], squareType);
                      square.setDisplaySize(squareSize, squareSize);
                      square.setInteractive();
                      square.on('pointerdown', function () {
                        // 切换图片索引
                        // currentGrid[row][col] = index;
                        // // 更新图像对象显示的图片
                        // square.setTexture(cubeKey[index]);
                        // ImageGrid[row-1][col].setTexture(cubeKey[index]);
                        if(!gameOn && stepCount !== 0 && type !== 'edit'){
                          oldIndex = currentGrid[row][col]
                          if( oldIndex == newIndex){
                            return
                          }
                          music.play()
                          step.text = --stepCount
                          gameHistory = [[row,col]]
                          gameIndex = 0
                          gameOn = true
                        }
                       
                    });
                    currentGrid[row][col] = parseInt(a)
                    ImageGrid[row][col] = square;
                  }
              }
        
  }
  

  // 更新方法（可选）
  update() {
    // 游戏循环逻辑
  
    if (gameOn) {
    
      if (frameCounter % 4== 0){
       let go = false
       const directions = [
        [-1, 0], // 上
        [1, 0],  // 下
        [0, -1], // 左
        [0, 1]   // 右
    ];
      let o = gameHistory.length
       while(gameIndex < o){
         let [row,col] = gameHistory[gameIndex]
         currentGrid[row][col] = newIndex
        ImageGrid[row][col].setTexture(cubeKey[newIndex])
        gameIndex++
        go = true
        for (let i = 0; i < directions.length; i++) {
          const [dx, dy] = directions[i];
          if (row + dx >= 0 && row + dx < gameGrid[0] && col + dy >= 0 && col + dy < gameGrid[1]) {
            const newRow = row + dx;
            const newCol = col + dy;
            const newType = parseInt(currentGrid[newRow][newCol]);
            if(newType === oldIndex){
               gameHistory.push([newRow,newCol])
            }
          }
        }
       }
       if(!go){
        gameOn = false
        music.stop()
        let res = [...new Set(currentGrid.flat().slice(0,80))]
        if(res.length ==1){
          if(type == 'test'){
            original =original.slice(0,98) + newIndex + (stepStart - stepCount)
            let shareCode = compressNumberString(original) + ";"
            let g = this.gameName.text
            let z = this.acticleName.text
            openModal('测试成功','您的分享码为 ：' + shareCode + g +"@" + z)
            type = 'edit'
            buttons.text = '开始测试'
          }
          if(type == 'game' && newIndex == parseInt(original[98])){
            
            gameList[gameNowIndex].completed = true
            localStorage.setItem('game', JSON.stringify(gameList))
            this.addWin()
          }
        }
       }   
    }
    frameCounter++
    if(frameCounter == 100){
      frameCounter = 0
    }
  }
    
  }
}

var startY = 150;
var startX = 100;

class ListScene extends Phaser.Scene {
  constructor() {
    super({ key: 'ListScene' }); // 场景标识符
    this.click = null
  }
  preload() {
  
    this.load.image('back', "img/back_l.png");
    this.load.image('left', "img/left.png");
    this.load.image('right', "img/right.png");
    this.load.audio('click', 'audio/click.mp3')
}

create() {
    
    this.click = this.sound.add('click');
    this.add.text(
      20,
      20,
      '溢彩画',
      {
          fontFamily: 'Arial',
          fontSize: 18,
          color: '#7F7042',
          stroke: '#000000',
          strokeThickness: 6
      }
  ).setOrigin(0,0);
  const textPage =  this.add.text(
    550,
    480,
    pageIndex + 1,
    {
        fontFamily: 'Arial',
        fontSize: 24,
        color: '#7F7042',
        stroke: '#000000',
        strokeThickness: 6
    }
)
  this.renderLevels(this);
  this.add.text(100 + startX,startY-50, '关卡名称      |     制作人       |   状态', { fontSize: '24px', fill: '#fff', fontStyle: 'bold' });
  createPopupButton2.call(this,800 ,40,"分享码", '#333',()=>{
    this.addshareCode()
    this.click.play()
  } )
  createPopupButton2.call(this,900 ,40,"创建关卡", '#333',()=>{
    original = '0'.repeat(100)
    type = 'edit'
    stepStart =  9
    stepCount =  9
      this.scene.start('MainScene');
      this.click.play()
  } )
  const back = this.add.image(1000, 40, 'back')
  back.setInteractive().on('pointerdown', () => {
    this.scene.start('StartScene');
    this.click.play()
  });
  const left = this.add.image(70, 300, 'left')
  .setDisplaySize(squareSize, squareSize)
  .setAlpha(0.2)
  .setInteractive().on('pointerdown', () => {
    pageIndex = Math.max(pageIndex - 1, 0);
    textPage.text =pageIndex +1;
    this.click.play();
    right.setAlpha(1);
    if(pageIndex == 0){
       left.setAlpha(0.2); 
    }
    this.renderLevels(this);
  })

  const right = this.add.image(1000, 300, 'right')
      .setDisplaySize(squareSize, squareSize)
      .setInteractive().on('pointerdown', () => {
        const  a = Math.floor(gameList.length / 8);
        pageIndex = Math.min(pageIndex + 1, a);
        this.click.play();
        textPage.text  = pageIndex +1
        left.setAlpha(1);
        if(pageIndex == a){
          right.setAlpha(0.2);
        }
        this.renderLevels(this);
      })
      
}

toClick(){
  if(!this.click.isPlaying){
    this.click.play();
  }
}
update(){

 
}
    


renderLevels(scene) {
  const elementsToDestroy = [];
  scene.children.each(child => {
      if (child.text && (child.text.includes('*') || child.text.includes('通过') || child.text.includes('挑战'))) {
          elementsToDestroy.push(child);
      }
  });

  // 统一销毁元素
  elementsToDestroy.forEach(child => child.destroy());
  var offsetY = 40;


  const r =gameList.slice(pageIndex*8,pageIndex*8 +8)
  console.log(r)
  r.forEach((level, index) => {
      const [name, author] = level.shareCode.split(";")[1].split('@');
      scene.add.text(100 +startX, startY + index * offsetY, '* ' + name +' *', { fontSize: '20px', fill: '#fff' });


      scene.add.text(320 + startX, startY + index * offsetY, '* ' +(author || '无名氏') + ' *', { fontSize: '20px', fill: '#fff' });
      const toGame = ()=>{
        this.toClick()
        original = decompressNumberString(gameList[index + pageIndex * 8].shareCode.split(";")[0])
        gameNowIndex = index + pageIndex * 8
        type = 'game'
        stepStart = parseInt(original[99])
        stepCount = stepStart
          this.scene.start('MainScene');
      }

      if (level.completed) {
          scene.add.text(550 +startX, startY + index * offsetY, '✓ 通过', { fontSize: '20px', fill: '#7F7042' });
          createPopupButton2.call(scene,720 +startX, startY +10 + index * offsetY,"重新挑战", 'green', toGame)
        } else {
          scene.add.text(550 + startX, startY + index * offsetY, '✗ 未通过', { fontSize: '20px', fill: '#FF0000' });
          createPopupButton2.call(scene,700 +startX, startY + 10 + index * offsetY,"挑战", 'red', toGame)
        }
     
  });
}

addshareCode() {
    // 创建弹出框背景

    const allInteractiveElements = this.children.list.filter(child => child.input && child.input.enabled);
    allInteractiveElements.forEach(element => {
        element.input.enabled = false;
    });
    const bg = this.add.graphics();
    bg.fillStyle(0x000000, 0);
    bg.fillRect(0, 0, this.cameras.main.width, this.cameras.main.height);
    bg.setDepth(1000); 


    const popupBackground = this.add.graphics();
    popupBackground.fillStyle(0x000000, 0.8);
    const popupWidth = 400;
    const popupHeight = 220;  // 增加高度以容纳标题
    const popupX = (this.cameras.main.width - popupWidth) / 2;
    const popupY = (this.cameras.main.height - popupHeight) / 2;
    popupBackground.fillRect(popupX, popupY, popupWidth, popupHeight);
    // 设置弹出框背景的深度，使其位于背景之上
    popupBackground.setDepth(1001); 

    // 添加标题
    const titleText = this.add.text(
        popupX + popupWidth / 2,
        popupY + 40,
        '分享码',
        {
          fontFamily: 'Arial' ,
            fontSize: '32px',
            color: '#FFFFFF',
            fontStyle: 'bold'
        }
    ).setOrigin(0.5);
    // 设置标题的深度，使其位于背景之上
    titleText.setDepth(1001); 

    // 显示输入框
    const inputField = document.getElementById('input');
    inputField.style.display = 'block';
    inputField.style.width = `${popupWidth - 100}px`;  // 设置输入框宽度
    // 创建通用按钮函数
    function createPopupButton(x, y, text, color, callback) {
        const button = this.add.text(x, y, text, {
            fontSize: '24px',
            color: color,
            backgroundColor: '#000000',
            padding: { x: 20, y: 10 },
            align: 'center'
        }).setOrigin(0.5);
        button.setInteractive().on('pointerdown', callback);
        // 设置按钮的深度，使其位于背景之上
        button.setDepth(1001); 
        return button;
    }

    // 创建按钮
    const buttonY = popupY + popupHeight - 60;
    const confirmButton = createPopupButton.call(
        this,
        popupX + popupWidth * 0.3,
        buttonY,
        '确认',
        '#00ff00',
        () => {
            this.toClick()
            console.log('输入的值是:', inputField.value);
            if (!decompressNumberString(inputField.value.split(";")[0])) {
                showMessage("分享码格式不对");
                return;
            }
            if (gameList.some(item => item.shareCode === inputField.value.split(";")[0])) {
                showMessage("分享码重复");
                return;
            }
            showMessage("添加成功");
            gameList.push({
                completed: false,
                shareCode: inputField.value
            });
            localStorage.setItem('game', JSON.stringify(gameList));
            hidePopup();
            this.renderLevels(this);

        }
    );

    const cancelButton = createPopupButton.call(
        this,
        popupX + popupWidth * 0.7,
        buttonY,
        '取消',
        '#ff0000',
        () =>{ 
          this.toClick()
          hidePopup()
        }
    );

    // 统一隐藏弹出框方法
    function hidePopup() {
        inputField.style.display = 'none';
        inputField.value = '';  // 清空输入内容
        popupBackground.clear();
        bg.clear();
        titleText.destroy();
        confirmButton.destroy();
        cancelButton.destroy();
        allInteractiveElements.forEach(element => {
          element.input.enabled = true;
      });
    }
}
}
var config = {
  type: Phaser.AUTO,
  width: 1100,
  height: 550,
  fps: {
    // 设置帧率上限为 30 帧每秒
    limit: 30
},
transparent: true,
backgroundColor: 0x00000000,
scale: {
  mode: Phaser.Scale.FIT,
  autoCenter: Phaser.Scale.CENTER_BOTH,
},
  scene: [StartScene,MainScene,ListScene]

};

function createPopupButton(x, y, text, color, callback) {
  return this.add.text(x, y, text, {
      fontSize: '24px',
      color: '#ffffff',
      backgroundColor: color,
      padding: { x: 20, y: 10 },
      shadow: { offsetX: 2, offsetY: 2, color: '#000', fill: true }
  })
  .setOrigin(0.5)
  .setInteractive()
  .on('pointerdown', callback);
}

function createPopupButton2(x, y, text, color, callback) {
  return this.add.text(x, y, text, {
      fontSize: '20px',
      color: '#ffffff',
      backgroundColor: color,
      padding: { x: 10, y: 5 },
      shadow: { offsetX: 2, offsetY: 2, color: '#000', fill: true }
  })
  .setOrigin(0.5)
  .setInteractive()
  .on('pointerdown', callback);
}
var game = new Phaser.Game(config);
